const Db = require('../services/mysql')
const { Fb, Moment, Op, Dev } = require('../class/utils')

class Address {
  /**
   * 新建城市
   */
  createCity(form) {
    return Db.City.create({
      cityname: form.cityname,
      delstatus: '否'
    })
  }

  /**
   * 新建地区
   */
  create(form) {
    return Db.Address.create({
      areaname: form.cityname,
      fatherid: form.fatherid,
      delstatus: '否'
    })
  }

  /**
   * 删除城市
   */
  delCity(form) {
    return Db.City.destroy({
      where: {
        id: form.id
      }
    })
  }

  /**
   * 删除地区
   */
  delArea(form) {
    return Db.Address.destroy({
      where: {
        id: form.id
      }
    })
  }

  /**
   * 地址列表
   */
  list(form, nowPage, pageSize) {
    return new Promise((resolve, reject) => {
      Db.City.findAndCountAll({
        where: {
          cityname: {
            [Op.like]: '%' + form.cityname + '%'
          },
          delstatus: '否'
        },
        order: [['cityname', 'DESC']],
        offset: pageSize * (nowPage - 1),
        limit: pageSize
      })
        .then(cityData => {
          Db.Address.findAll({
            where: {
              delstatus: '否'
            },
            order: [['cityname', 'DESC']]
          })
            .then(data => {
              cityData.areaData = data
              resolve(cityData)
            })
            .catch(err => {
              reject(err)
            })
        })
        .catch(err => {
          reject(err)
        })
    })
  }

  /**
   * 获取城市列表
   */
  getCityList() {
    return Db.City.findAll()
  }

  /**
   * 获取地区列表
   */
  getAllAreaList() {
    return Db.Address.findAll()
  }

  /**
   * 根据城市获取地区列表
   */
  getAreaList(form) {
    return Db.Address.findAll({
      where: {
        fatherid: form.fatherid
      }
    })
  }
}

module.exports = new Address()
